/**
 * @description 单个类的所有属性
 */

import { useEffect, useState, useContext } from 'react';
import { Form, Input, Button, Space, AutoComplete, message } from 'antd';
import { DeleteOutlined, CaretDownOutlined, CaretUpOutlined } from '@ant-design/icons';

import { UpdateContext } from '@/store/updateContext';
import { styleAttr, styleOption } from '@/utils/styleOptions';

let timer = null
let timer2 = null
function StyleWrapper({ form, preKeys, onStyleChange }) {

  const updateCtx = useContext(UpdateContext)
  const [formList, setFormList] = useState([])
  // json输入框
  const [jsonText, setJsonText] = useState()
  const [showJson, setShowJson] = useState(false)

  // 添加框
  const [code, setCode] = useState('')


  // 删除
  let closeChange = (key) => {
    let newFormList = formList.filter(code => code !== key)

    setFormList(newFormList)

    let formData = form.getFieldValue(preKeys)

    delete formData[key]

    form.setFieldValue(preKeys, formData)

    // 删除属性值的方式，删除属性？ 属性未删除，值时undefined
    // form.setFieldValue([...preKeys, key], undefined)

    // 更新json文本
    // let values = form.getFieldValue(preKeys)
    setJsonText(JSON.stringify(formData, null, 2))

    onStyleChange()
  }

  // 普通属性值变化
  let inputChange = () => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {

      let values = form.getFieldValue(preKeys)
      // 更新json文本
      setJsonText(JSON.stringify(values, null, 2))

      // TODO:更新样式
      onStyleChange()

      timer = null
    }, 300)
  }


  // json文本值变化
  let jsonChange = (e) => {
    let newValue = e.target.value

    setJsonText(newValue)

    if (timer2) {
      clearTimeout(timer2)
    }

    timer2 = setTimeout(() => {


      let returnFlag = true
      let newData

      if (newValue == "") {
        returnFlag = false
        newData = {}
      } else if (isJsonString(newValue)) {
        returnFlag = false
        newData = JSON.parse(newValue)
      }

      if (returnFlag) {
        return false
      }

      // 输入框的个数
      let newFormList = Object.keys(newData)
      setFormList(newFormList)

      // 输入框的值
      form.setFieldValue(preKeys, newData)

      onStyleChange()
    }, 300)

  }

  // 添加属性
  const addInput = () => {
    if (formList.includes(code)) {
      message.error('该属性已经存在')
      return
    }

    let newFormList = [...formList, code]

    setCode("")
    // 输入框的个数
    setFormList(newFormList)
  }

  useEffect(() => {
    let formData = form.getFieldValue(preKeys)
    setFormList(Object.keys(formData))
    setJsonText(JSON.stringify(formData, null, 2))
  }, [updateCtx.updateFlag])

  return (

    <>
      {/* 属性输入框 */}
      {
        formList.map(key => (
          <Form.Item
            key={key}
            label={styleAttr[key] || key}
            name={[...preKeys, key]}
          >
            <Input addonAfter={<DeleteOutlined onClick={() => closeChange(key)} />} onChange={() => inputChange(key)} />
          </Form.Item>
        ))
      }


      {/* json文本输入框 */}
      {
        showJson ?
          (
            <>
              <Button type="primary" size='middle' danger shape="circle" icon={<CaretUpOutlined />} onClick={() => setShowJson(false)} />
              <Input.TextArea size='middle' rows={4} value={jsonText} onChange={jsonChange} />
            </>
          )
          :
          <Button type="primary" size='middle' shape="circle" icon={<CaretDownOutlined />} onClick={() => setShowJson(true)} />
      }

      {/* 添加 */}
      <Space.Compact block style={{ marginTop: 10, justifyContent: 'center' }}>
        <AutoComplete
          showSearch
          filterOption={(input, option) =>
            option.name.toLowerCase().indexOf(input.toLowerCase()) != -1 ||
            option.value.toLowerCase().indexOf(input.toLowerCase()) != -1
          }

          placeholder="请选择样式"
          style={{
            flex: "1 1 auto",
          }}
          value={code}
          onChange={setCode}
          options={styleOption}
        />
        <Button onClick={addInput} >添加</Button>
      </Space.Compact>

    </>
  )
}

// 判断是否是合规的json字符串
function isJsonString(str) {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
}
export default StyleWrapper